﻿
using IDEAMS.common.converter;
using IDEAMS.core.opm;
using IDEAMS.core.queue;
using IDEAMS.model.device;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;

namespace IDEAMS.core.deviceClient
{
    [TypeConverter(typeof(EnumDescriptionTypeConverter))]
    public enum ConnectionStatus
    {
        [Description("未连接")]
        OFFLINE = 0,
        [Description("连接中")]
        CONNECTING,
        [Description("已连接")]
        CONNECTED
    }

    [TypeConverter(typeof(EnumDescriptionTypeConverter))]
    public enum DeviceStatus
    {
        [Description("连接中")]
        CONNECTING = 0,
        [Description("已连接")]
        CONNECTED,
        [Description("断开中")]
        DISCONNECTING,
        [Description("已断开")]
        DISCONNECTED
    }

    public class DeviceClient
    {
        private static ILog logger = LogManager.GetLogger(typeof(DeviceClient));

        private readonly object locker = new object();

        private DeviceStatus status;

        public DeviceDataWorker dataWorker;

        public ContinuousWorker continuousWorker;
        private Thread thContinuouisWoker;

        private Thread thWorker = null;
        private bool stopFlag = true;
        private bool stopFlagContinuous = true;

        public string ip;
        public int port;

        public DeviceParam deviceParam;

        /// <summary>
        /// 设备频率
        /// </summary>
        internal int frequency;

        public DeviceClient(string deviceIp, int devicePort)
        {
            this.status = DeviceStatus.DISCONNECTED;

            this.ip = deviceIp;
            this.port = devicePort;

            dataWorker = new DeviceDataWorker(deviceIp,devicePort);
        }

        public bool WaitConnected(int millisecond)
        {
            bool rn = false;
            int conuts = 5;
            int sleepTm = millisecond / 5;
            int i = 0;
            while (i < conuts)
            {
                if (dataWorker.GetStatus() == ConnectionStatus.CONNECTED)
                {
                    rn = true;
                    break;
                }

                i++;
                Thread.Sleep(sleepTm);
            }
            return rn;
        }

        public int Start(Action<DeviceParam,int> action)
        {
            int rn = 0;
            stopFlag = false;

            while(!stopFlag)
            {
                lock(locker)
                {
                    if (this.dataWorker.IsStop())
                    {
                        this.dataWorker.StartReceiveSync(action);
                        WaitConnected(1000);
                    }

                    if(dataWorker.GetStatus() == ConnectionStatus.CONNECTED)
                    {
                        status = DeviceStatus.CONNECTED;
                    }
                    else
                    {
                        status = DeviceStatus.DISCONNECTED;
                        Thread.Sleep(1000);
                    }
                }
            }

            StopAllWorkers();

            return rn;
        }

        public int StartAsync(Action<DeviceParam,int> action)
        {
            int rn = 0;

            //停止时才能启动，如果已启动不重复启动
            if (stopFlag)
            {
                thWorker = new Thread(new ThreadStart(() => Start(action)));
                if (thWorker != null)
                {
                    thWorker.Start();
                }
                else
                {
                    rn = -1;
                }
            }
            else
            {
                rn = -2;
            }
            return rn;
        }

        public void Stop()
        {
            stopFlag = true;
        }

        public void StopAllWorkers()
        {
            lock(locker)
            {
                dataWorker.DisConnect();
                dataWorker.StopReceive();
                this.status = DeviceStatus.DISCONNECTED;
                if (continuousWorker != null)
                {
                    continuousWorker.Stop();
                }
            }
        }

        public void Join()
        {
            dataWorker.Join();
        }

        public void Join(int milliseconds)
        {
            dataWorker.Join(milliseconds);
        }

        public DeviceStatus GetStatus()
        {
            lock(locker)
            {
                return status;
            }
        }

        public int Register(OPM_MsgWorker worker, QueueDataType key)
        {
            int rn = 0;
            List<QueueDataType> keyList = new List<QueueDataType>();
            keyList.Add(key);
            rn = Register(worker, keyList);

            return rn;
        }

        public int Register(OPM_MsgWorker worker, List<QueueDataType> keyList)
        {
            int rn = 0;
            int rn2 = 0;
            try
            {
                rn2 = dataWorker.msgDispatcher.Register(worker, keyList);
                if (rn2 != 0)
                {
                    logger.ErrorFormat("register失败");
                }
            }
            catch (Exception)
            {
                rn = -1;
            }
            return rn;
        }

        public void UnRegister(OPM_MsgWorker worker, QueueDataType key)
        {
            List<QueueDataType> keyList = new List<QueueDataType>();
            keyList.Add(key);
            UnRegister(worker, keyList);
            return;
        }
        public int UnRegister(OPM_MsgWorker worker, List<QueueDataType> keyList)
        {
            int rn = 0;
            try
            {
                lock (locker)
                {
                    dataWorker.msgDispatcher.UnRegister(worker, keyList);
                }
            }
            catch (Exception)
            {
                rn = -1;
            }
            return rn;
        }


        public int StartContinuousAsync()
        {
            int rn = 0;

            //停止时才能启动，如果已启动不重复启动
            if (stopFlagContinuous)
            {
                thContinuouisWoker = new Thread(new ThreadStart(() => StartContinuous()));
                if (thContinuouisWoker != null)
                {
                    thContinuouisWoker.Start();
                }
                else
                {
                    rn = -1;
                }
            }
            else
            {
                rn = -2;
            }
            return rn;
        }

        public int StartContinuous()
        {
            int rn = 0;
            continuousWorker = new ContinuousWorker(dataWorker.serialNo);
            Register(continuousWorker, QueueDataType.DATA_WL);
            if (continuousWorker != null && this.continuousWorker.IsStop())
            {
                dataWorker.isWaveStart = true;
                this.continuousWorker.StartAsync();
                dataWorker.OPMStart();
            }

            return rn;
        }

        public void StopContinuous()
        {
            if (continuousWorker != null)
            {
                UnRegister(continuousWorker, QueueDataType.DATA_WL);
                continuousWorker.Stop();
            }
            dataWorker.OPMStop_SendOnly();
            dataWorker.isWaveStart = false;
        }
    }
}
